/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 28
 * Time: 17:11
 */
//牛客 合并二叉树
public class Solution2 {
    //法一 官方推荐方法
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        if(t1 == null) return t2;
        if(t2 == null) return t1;
        //此时t1和t2都不为null
        t1.val = t1.val + t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees (t1.right, t2.right);
        return t1;
    }

    //法二 也是官方推荐方法 与法一不同的是创建一颗新树作为合并的二叉树
    public TreeNode mergeTrees1 (TreeNode t1, TreeNode t2) {
        //若只有一个节点返回另一个，两个都为null自然返回null
        if (t1 == null)
            return t2;
        if (t2 == null)
            return t1;
        //根左右的方式递归
        TreeNode head = new TreeNode(t1.val + t2.val);
        head.left = mergeTrees1(t1.left, t2.left);
        head.right = mergeTrees1(t1.right, t2.right);
        return head;
    }
}
